/*
 *Copyright(c) 2021 Shenzhen Kaihong Digital Industry DevelopmentCo.,Ltd
 *Licensed under the Apache License,Version2.0(the"License");
 *you may not use this file except in compliance with the License.
 *You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,software
 * distributed under the License is distributed on an "AS IS"BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.chinasoft.filter;


import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.chinasoft.utils.TokenUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {


    private String[] urls;

    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);


    public LoginInterceptor(String[] urls) {
        this.urls=urls;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        logger.info("the session is "+request.getSession().getId()+",the uri is"+request.getRequestURI());

        String uri = request.getRequestURI();
        for (String s : urls) {
            if (uri.indexOf(s) >= 0){
               return true;
            }
        }
       JSONObject jsonObject = new JSONObject();

        if(uri.indexOf("/error")>=0){
            response.setStatus(200);
            jsonObject.put("code",1);
            jsonObject.put("msg","请检查请求路径,参数,方法");
            response.getWriter().write(jsonObject.toJSONString());
            return false;
        }


        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            response.setStatus(200);
            jsonObject.put("code",1);
            jsonObject.put("msg","请先登录");
            response.getWriter().write(jsonObject.toJSONString());
            return false;
        }

        DecodedJWT jwt = TokenUtils.verify(token);
        if (null==jwt){
            response.setStatus(403);
            jsonObject.put("code",1);
            jsonObject.put("msg","token无效");
            response.getWriter().write(jsonObject.toJSONString());
            return false;
        }

        String loginUserId = jwt.getClaim("loginUserId").asString();

        if (StringUtils.isBlank(loginUserId)){
            response.setStatus(403);
            jsonObject.put("code",1);
            jsonObject.put("msg","token解析出错");
            response.getWriter().write(jsonObject.toJSONString());
            return false;
        }

        HttpSession session = request.getSession();
        session.setAttribute("loginUserId",loginUserId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    public String getUserInfoFromUser(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("userInfo_myCookies")) {
                    String userInfo = cookie.getValue();
                    if (!StringUtils.isBlank(userInfo)){
                         return cookie.getValue();
                    }else {
                        return null;
                    }
                }
            }
        }
        return null;
    }
}
